class Judge {
  constructor(app) {
    this.app = app;
  }


  async startJudge() {
    this.judge();
  }

  async judge() {
    console.log('开始判题');
    const res = await this.app.rabbitmq.consumeMessages();
    if (res) {
      try {
        const examId = res.exam_id;
        const userId = res.user_id;
        const userExam = await this.app.mysql.get('exam_user', { user_id: String(userId), exam_id: String(examId) });
        const systemExam = await this.app.mysql.get('exam_paper', { id: userExam.used_paper_id });
        const userAnswer = [];
        const systemAnswer = [];
        const sysContent = JSON.parse(systemExam.content);
        const userContent = JSON.parse(userExam.submit_res);
        sysContent.forEach((bigQues, bigIndex) => {
          bigQues.ques.forEach((smallQues, smallIndex) => {
            systemAnswer.push({
              title: smallQues.title_text,
              answer: smallQues.answer,
              answer_text: smallQues.answer_text,
              score: smallQues.score,
            });
            userAnswer.push({
              answer: JSON.stringify(userContent[bigIndex].ques[smallIndex].answer),
            });
          });
        });
        await this.app.openai.getScore(JSON.stringify(systemAnswer), JSON.stringify(userAnswer)).then(async res => {
          const target = JSON.parse(res);
          let ind = 0;
          userContent.forEach(bigQues => {
            bigQues.ques.forEach(smallQues => {
              smallQues.score = target.list[ind++];
            });
          });
          const tem = JSON.stringify(userContent);
          await this.app.mysql.update('exam_user', { total_score: target.total_score, state: 2, judge_res: tem }, { where: { exam_id: examId, user_id: userId } });
          console.log('判题成功-结束');
        }).catch(error => {
          console.log('判题失败-结束', error);
        });
      } catch (error) {
        console.log('判题失败-结束', error);
      }
      setTimeout(() => {
        this.judge();
      }, 3000);
    } else {
      setTimeout(() => {
        this.judge();
      }, 60000);
    }
  }


  async endJudge() {
    console.log('结束判题');
  }
}

module.exports = Judge;
